import numpy as np
import matplotlib.pyplot as plt

# 1.数据集的输入
data = [[0.8,1.0],[1.7,0.9],[2.7,2.4],[3.2,2.9],[3.7,2.8],[4.2,3.8],[4.2,2.7]]
data = np.array(data)
#将特征与标签分离
x_data = data[:,0]
y_data = data[:,1]
# 2. 前向计算
# y = wx + b
step = 5
w = 1
w_old = w
b = 0
y_bar = w * x_data + b
# 3.单点误差
e_bar = y_data - y_bar

# 4.均方误差
e_pre = np.mean(e_bar ** 2)
print(f"均方误差：{e_pre}")

learning_rate = 0.01
for i in range(step):
    # 5.绘制图像
    fig = plt.figure(figsize=(10,5))
    ax1 = fig.add_subplot(1,2,1)
    ax2 = fig.add_subplot(1,2,2)
    step = 5

    gradient = 2 * w_old * np.mean(x_data**2)-2 * np.mean(x_data * y_data)#w_old所在点的切线的斜率
    w_new= w_old -learning_rate*gradient

    #求出w_new出的损失值
    y_new= w_new * x_data + b
    e_new = np.mean(y_new -y_data)**2
    print(f"损失：{e_new}")


    #绘制第一个图像
    """
    1.限制x,y的范围,设置标签
    2.绘制数据集散点
    3.绘制直线
    """
    ax1.set_xlim(0,5)
    ax1.set_ylim(0,6)
    ax1.set_xlabel('x')
    ax1.set_ylabel('y')

    ax1.scatter(x_data,y_data,color='b')

    y1 = w_new*0+b
    y2 = w_new*5+b
    ax1.plot([0,5],[y1,y2],color='r',linewidth=3)

    #绘制第二个图像
    ax2.set_xlim(0,3)
    ax2.set_ylim(0,20)
    w_values = np.linspace(0,3,100)
    e_values = [np.mean((y_data-(w_value * x_data+b))**2) for w_value in w_values]
    ax2.plot(w_values,e_values,color='g',linewidth=3)
    ax2.plot(w_new,e_new,marker="o",color='b',linewidth=3)
    plt.pause(1)
    w_old = w_new
    print(w_old)


plt.show()




